import 'dart:convert';

void main() {
  List<DrawModel> list = List();
  UserModel zs = new UserModel("zhangsang", 18);
  UserModel ls = new UserModel("李四", 25);

  // jsonEncode(user) 时如果 user 类没有toJson方法则会抛 Converting object to an encodable object failed: Instance of 'DrawModel'
  var encode = json.encode(zs);
  print(encode);

  list.add(DrawModel(1, 'aaa', 'url', zs));
  list.add(DrawModel(2, 'bbb', 'url', ls));
  // print(list);

  List<String> datas = list.map((DrawModel item) {
    return jsonEncode(item);
  }).toList();
  print(datas);

  List<DrawModel> list1 = datas.map<DrawModel>((v) {
    return DrawModel.fromJson(json.decode(v));
  }).toList();

  list1.forEach((DrawModel v) {
    print("id: ${v.id} user: ${v.user}");
  });
}

// 图纸实体
class DrawModel {
  int id;
  String name;
  String url;
  UserModel user;

  DrawModel(this.id, this.name, this.url, this.user);

  // 通过传入 json 数据转换成数据模型
  DrawModel.fromJson(String jsonString) {
    Map<String, dynamic> data = json.decode(jsonString);
    id = data['id'];
    name = data['name'];
    url = data['url'];
    user = UserModel.fromJson(jsonDecode(data['user']));
  }

  String toJson() {
    return json.encode(this.toMap());
  }

  // 将数据模型转换成 json
  Map<String, dynamic> toMap() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = id;
    data['name'] = name;
    data['url'] = url;

    data['user'] = json.encode(user);
    return data;
  }

  // 重写==实现对象判断
  @override
  bool operator ==(other) {
    // 检测类型是否匹配
    if (other is! DrawModel) {
      return false;
    }

    // 比较属性是否相同
    final DrawModel obj = other;
    return id == obj.id;
  }

  @override
  String toString() {
    return 'DrawModel{id: $id, name: $name}';
  }
}

class UserModel {
  String name;
  int age;

  UserModel(this.name, this.age);

  UserModel.fromJson(String jsonString) {
    Map<String, dynamic> map = json.decode(jsonString);
    this.name = map['name'];
    this.age = map['age'];
  }

  // json.encode(user) 时会调用此方法
  String toJson() {
    return json.encode(this.toMap());
  }

  Map<String, dynamic> toMap() {
    Map<String, dynamic> map = Map();
    map['name'] = name;
    map['age'] = age;

    return map;
  }

  @override
  String toString() {
    return 'UserModel: {name: $name, age: $age}';
  }
}
